<template>
  <view class="infoclass">
    <div class="topBg">
      <div
        style="
          width: 100vw;
          height: 95px;
          padding-top: 50px;
          position: relative;
          display: flex;
          justify-content: center;
          line-height: 64rpx;
        "
      >
        <div style="position: absolute; left: 30rpx; top: 105rpx">
          <u-icon
            @click="rightClick"
            name="arrow-left"
            color="#fff"
            size="44"
          ></u-icon>
        </div>
        <div style="color: #fff; font-size: 36rpx">提交订单</div>
      </div>
      <div
        style="height: 155rpx; width: 100vw; display: flex; align-items: center"
      >
        <div style="color: #fff; padding-left: 18px; padding-top: 20px">
          <div style="font-size: 20px; font-weight: 500">订单待提交</div>
          <div style="font-size: 14px; font-weight: 500">
            尽快提交，平台优先安排哦~
          </div>
        </div>
      </div>
    </div>
    <view class="order_buy">
      <!-- 地址卡片 -->

      <view
        class="card"
        @click="goPage('/bundle/pages/user_address/index?type=true')"
      >
        <view class="card--header flex justify-between">
          <template v-if="!orderData.userAddressDetailVo">
            <view class="title pt-[20rpx]">请选择地址</view>
          </template>
          <template v-else>
            <view class="title">
              <img
                src="http://mzd-admin.muzhandao.com/api/uploads/image/20240905/7e483fd7-4b3d-45e7-b0bc-a3e7671bfd23.png"
                style="width: 36rpx; height: 36rpx; margin-right: 10rpx"
                alt=""
              />{{ orderData.userAddressDetailVo.province }}
              {{ orderData.userAddressDetailVo.city }}
              {{ orderData.userAddressDetailVo.district }}
              {{ orderData.userAddressDetailVo.address }}</view
            >
          </template>

          <u-icon name="arrow-right" color="#707070" size="22"></u-icon>
        </view>
        <template v-if="orderData.userAddressDetailVo">
          <view class="text-sm text-muted" style="padding-left: 42rpx">
            {{ orderData.userAddressDetailVo?.contact }}
            {{ orderData.userAddressDetailVo?.mobile }}
          </view>
        </template>
      </view>

      <!-- 商品卡片 -->
      <view class="card">
        <view class="goods-item">
          <u-image
            :src="orderData.imageUrl"
            width="160"
            height="160"
            border-radius="4"
          ></u-image>
          <view class="ml-[20rpx] mt-[4rpx]">
            <view class="flex justify-between title">
              <!-- <view class="goods-item--name truncate">{{ orderData.goodsName }}</view> -->
              <view class="goods-item--name truncate">{{
                orderData.goodsSpecificationDetailVo.goodsName ||
                "" + "【" + goodsSpecificationDetailVoname() + "】"
              }}</view>
              <text class="num">x{{ goodsForm.goods_num }}</text>
            </view>
            <view class="mt-[24rpx]" style="display: flex">
              <div style="line-height: 28px; color: red">￥</div>
              <div style="color: red; font-size: 18px">
                {{ orderData.totalPrice }}
              </div>
              <div style="line-height: 28px; margin-left: 5px">/次</div>
              <!--   <price
              :price=""
              :desc="orderData.unitName"
            ></price> -->
            </view>
          </view>
        </view>
      </view>

      <!-- 上门时间 -->

      <view
        class="card flex justify-between"
        style="height: height: 96rpx;"
        @click="
          goPage(
            `/bundle/pages/appoint_time/index?appointTime=${JSON.stringify(
              appointTime
            )}`
          )
        "
      >
        <view
          class="normal text-base font-medium"
          style="display: flex; align-items: center"
          ><img
            src="http://mzd-admin.muzhandao.com/api/uploads/image/20240905/96906d63-dc4a-4e4b-bc57-fd45735cfe0b.png"
            style="width: 36rpx; height: 36rpx; margin-right: 10rpx"
            alt=""
          />上门时间</view
        >
        <view class="flex">
          <text class="mr-[20rpx] text-sm text-black">{{ appoint }}</text>
          <u-icon name="arrow-right" color="#707070" size="22"></u-icon>
        </view>
      </view>
      <view
        class="card flex justify-between"
        @click="goPage(`/pages/order_buy/youhuiquan?id=` + goodsForm.id)"
      >
        <view class="normal text-base font-medium">优惠券</view>
        <view class="flex">
          <text class="mr-[20rpx] text-sm text-black">{{ couponName }}</text>
          <!-- <text class="mr-[20rpx] text-sm text-black">{{ appoint }}</text> -->
          <u-icon name="arrow-right" color="#707070" size="22"></u-icon>
        </view>
      </view>
      <!-- 备注 -->
      <view class="card">
        <view class="normal text-lg font-medium">备注</view>
        <view class="mt-[10rpx]">
          <u-input
            v-model="userRemark"
            type="textarea"
            placeholder="请填写您的特殊需求"
            height="124"
          />
        </view>
      </view>

      <!-- 服务金额 -->
      <view
        class="card"
        style="
          background-image: url('http://mzd-admin.muzhandao.com/api/uploads/image/20240905/4d71401d-7735-44a5-bc98-eded7a5dc188.png');
          background-size: 100% 100%;
          height: 96rpx;
        "
      >
        <view class="flex justify-between normal text-base">
          <view class="font-medium"></view>
          <view
            style="
              font-weight: 500;
              font-size: 18px;
              color: #8456ff;
              line-height: 25px;
            "
            >{{ `¥${orderData.totalPrice}` }}</view
          >
        </view>
        <!-- todo -->
        <!-- <view class="mt-4 flex justify-between normal text-base">
                <view class="font-medium">服务金额</view>
                <view @tap="showCoupons = true">
                    <span class="rounded-full bg-primary py-1 px-2 mr-2 text-white">3张可用</span>
                    <u-icon name="arrow-right" color="#707070" size="22"></u-icon>
                </view>
            </view> -->
      </view>

      <view class="footer flex justify-between items-center">
        <view class="text-primary">
          <text class="text-base" style="color: rgba(34, 34, 34, 1)"
            >需支付：</text
          >
          <text class="font-medium text-4xl" style="color: rgba(253, 86, 54, 1)"
            >¥{{ couponAmountUpdate(orderData.totalPrice) }}</text
          >
        </view>
        <view class="btn">
          <button
            style="
              width: 208rpx;
              height: 80rpx;
              margin-right: 0;
              background-image: url('http://mzd-admin.muzhandao.com/api/uploads/image/20240905/3cec18e0-272b-47e6-a031-e00e095a6805.png');
              background-size: 100% 100%;
              background-color: #fff !important;
            "
            class="bg-primary text-lg text-white leading-[80rpx] h-[80rpx]"
            @tap="onSubmitOrder"
          ></button>
        </view>
      </view>

      <!-- Component 页面状态 -->
      <!-- <page-status ref="pageRef"></page-status> -->

      <!-- Component 支付 -->
      <payment
        v-if="payState.showPay || payState.showCheck"
        ref="paymentRef"
        v-model:show="payState.showPay"
        v-model:show-check="payState.showCheck"
        :order-id="payState.orderId"
        :order_amount="orderData?.totalPrice"
        :from="payState.from"
        :redirect="payState.redirect"
        :amount="couponAmountUpdate(orderData.totalPrice)"
        :qcodevalue="qcodeVal"
        @success="handlePayResult"
        @close="handlePayResult"
        @fail="handlePayResult"
      />

      <u-popup
        v-model="showCoupons"
        mode="bottom"
        border-radius="14"
        :closeable="false"
        :safe-area-inset-bottom="true"
      >
        <view class="coupons">
          <view class="coupons-header">
            <text class="mx-auto">选择优惠券</text>
            <u-icon name="close" color="#666666" @tap="showCoupons = false" />
          </view>

          <view class="coupons-main">
            <scroll-view
              :scroll-y="true"
              style="height: 700rpx; touch-action: none"
            >
              <view
                class="coupons-item"
                v-for="item in [1, 2, 3, 2, 3, 2, 3, 2, 3]"
                :key="item"
              >
                <coupon-card
                  :item="item"
                  :showBtn="false"
                  :showSelect="true"
                  v-model="selectCoupon"
                />
              </view>
              <view class="text-center text-xs py-6 text-[#999]">
                以下此订单暂不适用
              </view>
              <view
                class="coupons-item-mask"
                v-for="item in [1, 2, 3, 2, 3, 2, 3, 2, 3]"
                :key="item"
              >
                <coupon-card :item="item" :showBtn="false" :status="0" />
              </view>
              <u-empty
                v-if="![1, 2, 3].length"
                text="暂无优惠券"
                src="http://mzd-admin.muzhandao.com/api/uploads/image/20240905/6905c04c-955b-4bed-90d7-1c749122a03d.png"
                :icon-size="180"
              />
            </scroll-view>
          </view>

          <view class="coupons-footer px-4 pb-1">
            <button
              class="bg-primary text-lg text-white leading-[80rpx] h-[80rpx] rounded-full"
              @tap="onSubmitOrder"
            >
              确定
            </button>
          </view>
        </view>
      </u-popup>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, shallowRef } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
  apiPlaceOrder,
  apiInitOrder,
  apigenerationgetCacheCode,
} from "@/api/order";
import Price from "@/components/price/index.vue";
import { useLockFn } from "@/hooks/useLockFn";
const couponName: any = ref("");
const paymentRef = shallowRef();
const orderData = ref<any>({
  userAddressDetailVo: {},
});
const qcodeVal = ref("");
const appointTime = ref<any>({
  year: "",
  date: "",
  start_time: "",
  end_time: "",
  orderStatus: null,
});
const userRemark = ref<string | null>("");
const addressId = ref<number | string | null>("");
const goodsForm = ref<any>({
  goods_num: "",
  id: "",
  goodsoutNumber: 0,
  isBuyFlag: 0,
});
const isBuyFlag = ref(0);
const isBuy_id = ref(0);
const couponId = ref<Array<number>>([]);
const codeData = ref<any>({
  goods_num: "",
  id: "",
});
const payState = reactive({
  orderId: "",
  from: "",
  showPay: false,
  showCheck: false,
  redirect: "/pages/order_buy/index",
});
const isscanCode = ref();
// 预约上门时间
const appoint = computed(() => {
  if (
    !appointTime.value.date &&
    isscanCode.value != "1" &&
    isscanCode.value != 1
  ) {
    return "请选择时间";
  } else if (isscanCode.value == "1" || isscanCode.value == 1) {
    appointTime.value.year = new Date().getFullYear();
    const date = new Date();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    appointTime.value.date = `${month}-${day}`;
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    appointTime.value.start_time = `${hours}:${minutes}`;
    date.setHours(date.getHours() + 2);
    const hours2 = String(date.getHours()).padStart(2, "0");
    const minutes2 = String(date.getMinutes()).padStart(2, "0");
    appointTime.value.end_time = `${hours2}:${minutes2}`;
    console.log(appointTime.value);
    return "当前时间";
  }
  return `${appointTime.value.date} ${appointTime.value.start_time}-${appointTime.value.end_time}`;
});

const goodsSpecificationDetailVoname = () => {
  let DetailVoname = orderData.value.goodsSpecificationDetailVo.name;
  if (DetailVoname.includes(">")) {
    let name_list = DetailVoname.split(">");
    DetailVoname = "";
    DetailVoname =
      DetailVoname + name_list[0] + ":" + goodsForm.value.goodsoutNumber;
    if (name_list[0].includes("面积")) DetailVoname += "㎡";
  } else {
  }

  return DetailVoname;
};

// 优惠券弹窗
const showCoupons = ref(false);
const selectCoupon = ref(0);

// 初始化下单数据
const initPlaceOrder = async (): Promise<void> => {
  console.log(initPlaceOrder);
  let num = 0;
  if (goodsForm.value.goodsoutNumber > 1) {
    num = goodsForm.value.goods_num * goodsForm.value.goodsoutNumber;
  } else {
    num = goodsForm.value.goods_num;
  }

  try {
    orderData.value = await apiInitOrder({
      goodsId: goodsForm.value.id,
      goodsNum: num,
      isBuyFlag: uni.getStorageSync("isBuyFlag"),
    });
    let isBuyFlag = uni.getStorageSync("isBuyFlag");
    if (orderData.value.buyNumber && isBuyFlag == 1) {
      orderData.value.goodsPrice = orderData.value.buyNumber;
    }
    addressId.value = orderData.value.userAddressDetailVo?.id;
  } catch (error) {
    uni.$u.toast(error);
  }
};

// 1. 确认提交订单
const { lockFn: onSubmitOrder } = useLockFn(async () => {
  const modal: any = await uni.showModal({
    title: "温馨提示",
    content: "是否确认下单?",
  });
  if (!modal.confirm) return;
  handlePlaceOrder();
});

// 2. 下单处理
const handlePlaceOrder = async (): Promise<void> => {
  if (!addressId.value) return uni.$u.toast("请先去选择地址");
  if (orderData.value.totalPrice <= 0) return uni.$u.toast("订单金额需大于0");

  const params = {
    appointTimeStart:
      Date.parse(
        `${appointTime.value.year}/${appointTime.value.date.replace(
          /-/g,
          "/"
        )} ${appointTime.value.start_time}`
      ) / 1000,
    appointTimeEnd:
      Date.parse(
        `${appointTime.value.year}/${appointTime.value.date.replace(
          /-/g,
          "/"
        )} ${appointTime.value.end_time}`
      ) / 1000,
    goodsId: goodsForm.value.id,
    orderAmount: orderData.value.totalPrice,
    orderTerminal: 1,
    orderType: 1, // 普通订单
    payWay: 1, // 临时
    staffId: 1, // 临时
    totalAmount: orderData.value.totalPrice,
    totalNum: goodsForm.value.goods_num * goodsForm.value.goodsoutNumber,
    userRemark: userRemark.value,
    addressId: addressId.value,
    isBuy: isBuyFlag.value,
    orderId: isBuy_id.value,
    couponId: couponId.value,
    isGratis: qcodeVal.value ? "1" : "0",
    isBuyFlag: uni.getStorageSync("isBuyFlag"),
    orderStatus: appointTime.value.orderStatus || null,
  };

  if (uni.getStorageSync("zfuserId")) {
    let zfuserId = uni.getStorageSync("zfuserId");
    params.scanUserId = zfuserId;
  }
  try {
    const data = await apiPlaceOrder({ ...params });
    payState.orderId = data.id;
    payState.from = "order";
    payState.showPay = true;
  } catch (err) {
    console.log("创建订单", err);
  }
};

const handlePayResult = async () => {
  payState.showPay = false;
  payState.showCheck = false;
  /* uni.redirectTo({
    url: `/pages/order/index?type=0`,
  }); */
  uni.navigateTo({
    url: `/pages/order_detail/index?id=${payState.orderId}&paytype=${1}`,
  });
};

// 跳转页面方法
const goPage = (url: string) => {
  uni.navigateTo({
    url,
  });
};
const couponAmount = ref();
const couponAmountUpdate = (data: any) => {
  if (parseFloat(data) >= parseFloat(couponAmount.value)) {
    return (parseFloat(data) - parseFloat(couponAmount.value)).toFixed(2);
  } else if (couponAmount.value == null) {
    return data;
  } else {
    return 0;
  }
};
const decodeAndSplitString = (str: string) => {
  const pairs = str.split("&");
  const result: { [key: string]: string } = {};

  pairs.forEach((pair) => {
    const [key, value] = pair.split("=");
    result[key] = value;
  });

  return result;
};
onLoad(async (options: any) => {
  console.log("555555555555555555555");
  if (options.scene) {
    console.log("这是一个扫码进来的", options.scene);
    console.log("这是一个扫码进来的", options);
    qcodeVal.value = options.scene;
    let res = await apigenerationgetCacheCode({ code: options.scene });
    console.log(decodeAndSplitString(res));
    console.log("===========");
    let codedata = decodeAndSplitString(res);
    goodsForm.value.goods_num = codedata.goodsNum;
    goodsForm.value.id = codedata.goodsSpecificationId;
  } else {
    isscanCode.value = uni.getStorageSync("isscanCode");
    const parseObj = JSON.parse(decodeURIComponent(options.params));
    const { goodsData, appointData } = parseObj;
    console.log(appointData);
    console.log(
      "goodsDatagoodsDatagoodsDatagoodsDatagoodsDatagoodsDatagoodsDatagoodsDatagoodsData"
    );

    goodsForm.value = goodsData;
    appointTime.value = appointData;
  }

  // 监听上门时间选择
  uni.$on("appointTime", (event) => {
    appointTime.value = event;
  });
  // 监听地址选择
  uni.$on("address", (event) => {
    orderData.value.userAddressDetailVo = event;

    addressId.value = event.id;
    return;
  });
  // 监听优惠券选择

  uni.$on("coupon", (event) => {
    console.log("优惠券选择的是： ", event);

    couponId.value.push(event.id);
    couponAmount.value = event.amount;
    couponName.value = event.name;
    console.log("优惠券的获取id是： ", couponId.value);
    return;
  });

  // 初始化订单信息
  await initPlaceOrder();
  if (options.checkPay == "true") {
    payState.orderId = options.order_id;
    payState.from = "order";
    payState.showCheck = true;
  }

  isBuyFlag.value = uni.getStorageSync("isBuyFlag") || 0;
  console.log(isBuyFlag.value, "isBuyFlag");

  isBuy_id.value = uni.getStorageSync("isBuy_id") || 0;
  if (isBuy_id.value != 0) {
    isBuyFlag.value = 1;
  }
  console.log(isBuy_id.value, "isBuy_id");
});

const rightClick = () => {
  uni.navigateBack({
    delta: 1, // 默认值是1，表示返回的页面层数
  });
};
</script>

<style lang="scss">
.infoclass {
  background-color: rgba(244, 244, 244, 1);
}
.topBg {
  background: url("http://mzd-admin.muzhandao.com/api/uploads/image/20240905/616405b5-39cd-4790-80e9-c608ff45ffb0.png");
  background-size: 100% 100%;
  width: 100vw;
  height: 444rpx;
}
.order_buy {
  padding: 40rpx 24rpx;
  /* background: linear-gradient(to bottom, #6b3da3 200rpx, transparent 0); */
  margin-top: -55px;
  .card {
    padding: 24rpx;
    margin-bottom: 20rpx;
    background-color: #fff;
    border-radius: 20rpx;

    &--header {
      padding-bottom: 20rpx;
    }
    .title {
      color: rgba(16, 16, 16, 1);
      font-size: 32rpx;
      .num {
        font-size: 28rpx;
        color: #666;
      }
    }
  }

  .goods-item {
    display: flex;
    &--name {
      width: 430rpx;

      // line-1
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }

  .footer {
    left: 0;
    bottom: 0;
    width: 100%;
    position: fixed;
    padding: 20rpx 30rpx;
    background: #ffffff !important;
    box-shadow: 2rpx 2rpx 22rpx rgba($color: #000000, $alpha: 0.2);
    padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);

    .btn {
      width: 320rpx;
      height: 100%;
    }
  }
}
.coupons {
  background-color: #f6f6f6;

  &-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100rpx;
    padding: 0 30rpx;
    font-weight: 500;
    font-size: 28rpx;
    background-color: #ffffff;
  }

  &-main {
    padding: 20rpx;

    .coupons-item {
      &:nth-child(n + 2) {
        margin-top: 20rpx;
      }
    }
  }
}
</style>
